<template>
    <rx-layout>
        <div slot="left" width="200" showButton="true" style="padding: 10px" >
            <a-input style="margin-bottom: 8px" :placeholder="i18n('title.dimension','搜索维度')" v-model="searchValue" @change="handleChange" ref="searchInput" >
                <a-icon slot="prefix" type="search" />
                <a-icon v-if="searchValue" slot="suffix" type="close-circle" @click="emitEmpty" />
            </a-input>
            <rx-vue-tree
                v-model="selectedKeys"
                :tree-data="dimTree"
                :showCheckbox="false"
                @rowClick="handleDimSelectRxVueTree"
                :expandedKeys.sync="expandedKeys"
            >
            </rx-vue-tree>
        </div>
        <div slot="center">
            <rx-fit>
                <div slot="toolheader" border="false" foldbtn="false">
                    <div class="table-operator">
                        <a-button @click="addGroup" icon="plus" type="primary" >
                            {{$ti18('rxList.newBtn','新建')}}
                        </a-button>
                    </div>
                </div>
                <!--
                /api-user/user/org/osGroup
                -->
                <rx-grid
                    class="rx-tree-title"
                    ref="table"
                    :bordered="isBorder"
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :showPage="false"
                    :columns="columns"
                    :defaultPageSize="10"
                    :dataSource="tableData"
                    @selectChange="onSelectGroupChange"
                    @rowExpand="rowExpand"
                    @rowClick="customRow"
                    :expandIconColumnIndex="2"
                    :pageSizeOptions="['10','30','40']"
                    :idField="'groupId'"
                >
                    <div  slot="name" class="rx-table-row-icon" slot-scope="{text,record}">
                        <span class="rx-tree-icon"><a-icon type="team" /></span>
                        <div class="telist rx-tree-title" :title="text">{{text}}</div>
                    </div>
                    <span slot="rankLevel" slot-scope="{text}" v-html="rankLevelFilter(text)">
                 </span>
                    <span slot="action" slot-scope="{ text, record }" class="actionIcons">
                        <span v-show="dimObj.isGrant=='YES'" @click="assignMenu(record)" >
                            {{i18n('button.menuAuthorization','菜单授权')}}
                        </span>
                        <span v-show="editEnable" @click="editGroup(record)">
                            {{$ti18('rxList.editBtn','编辑')}}
                        </span>
                        <a-divider type="vertical" />
                        <span v-show="editEnable && dimObj.showType=='TREE'" @click="editSub(record)">
                            {{i18n('button.subgroup','新增子组')}}
                        </span>
                        <span @click="setParent(record)">
                            {{i18n('button.migration','父级迁移')}}
                        </span>
                        <span @click="delByGroupIds([record.groupId])" v-show="removeEnable">
                            {{$ti18('rxList.delBtn','删除')}}
                        </span>
                        <span @click="setProprety(record)">
                             {{i18n('button.xAttrs','扩展属性')}}
                        </span>
                  </span>

                </rx-grid>
            </rx-fit>
        </div>
        <div slot="right" showButton="true" style="" width="450" style="padding: 10px">
            <a-tabs defaultActiveKey="user" @change="mainChange">
                <a-tab-pane :tab="i18n('title.userRelations','用户关系')" key="user">
                    <div>
                        <div class="table-operator">
                            <a-button @click="addUser()" type="primary" >
                                {{$ti18('rxList.newBtn','新建')}}
                            </a-button>
                            <a-button  v-show="removeEnable" type="danger" icon="delete" @click="delByUserId()">
                                {{$ti18('rxList.removeBtn','移除')}}
                            </a-button>
                            <a-button @click="joinUser()"  >
                                {{ i18n('isButton.join','加入') }}
                            </a-button>
                            <!-- <a-button @click="userSearch()" >查询</a-button> -->
                        </div>
                        <div class="table-page-search-wrapper">
                            <a-form layout="inline">
                                <a-row :gutter="24">
                                    <a-col :span="9">
                                        <a-input :placeholder="$comi18('rxDialog.fullName', '请输入姓名','input')" v-model="fullname" @pressEnter="userSearch"/>
                                    </a-col>
                                    <a-col :span="9">
                                        <a-input  :placeholder="i18n('form.userID','请输入用户编号','input')" v-model="userNo" @pressEnter="userSearch"/>
                                    </a-col>
                                    <a-col :span="6">
                                        <a-button @click="userSearch" >
                                            {{$ti18('rxList.searchBtn', '查询')}}
                                        </a-button>
                                    </a-col>
                                </a-row>
                            </a-form>
                        </div>
                    </div>
                    <a-tabs v-model="userActiveKey" @change="userChange" class="atbliat">
                        <a-tab-pane v-for="pane in userPanes" :tab="pane.title" :key="pane.key" :closable="pane.closable"
                                    forceRender>
                            <user-list-component :rel-type-id="pane.relTypeId" :group-id="currentGroupId" :tenant-id="tenantId" :ref="pane.key"/>
                        </a-tab-pane>
                    </a-tabs>
                </a-tab-pane>
                <a-tab-pane :tab="i18n('title.relation','组关系')" key="group" forceRender v-show="groupActiveKey">
                    <div>
                        <div class="table-operator">
                            <a-button @click="addGroupRelType()" icon="plus" type="primary" >
                                {{$ti18('rxList.newBtn','新增')}}
                            </a-button>
                            <a-dropdown v-show="removeEnable">
                                <a-button type="danger" icon="delete" @click="removeGroupRelType()">
                                    {{$ti18('rxList.removeBtn','移除')}}
                                </a-button>
                            </a-dropdown>
                        </div>
                    </div>

                    <a-tabs v-model="groupActiveKey" @change="groupChange" class="atbliat">
                        <a-tab-pane v-for="pane in groupPanes" :tab="pane.title" :key="pane.key" :closable="pane.closable"
                                    forceRender>
                            <group-list-component :rel-type-id="pane.relTypeId"
                                                  :dim-id2="pane.dimId2"
                                                  :group-id="currentGroupId"
                                                  :tenant-id="tenantId"
                                                  :ref="pane.key"/>
                        </a-tab-pane>
                    </a-tabs>
                </a-tab-pane>
            </a-tabs>
        </div>
    </rx-layout>
</template>

<script>
import OsGroupEdit from "../modules/user/org/OsGroupEdit.vue"
import UserListComponent from '../modules/user/org/UserListComponent.vue'
import GroupListComponent from '../modules/user/org/GroupListComponent.vue'
import GroupProperties from '../modules/user/org/GroupProperties.vue'
import osPropertiesGroupApi from '@/api/user/org/osPropertiesGroup'
import OsGroupExt from '@/api/user/org/osGroupExt'
import OsGroupApi from '@/api/user/org/osGroup'
import { BaseList, RxLayout,RxGrid,RxFit,Util,Dialog } from "@lowcode/jpaas-common-lib"

export default {
    name: 'TableList',
    mixins: [BaseList,OsGroupExt],
    components: {
        OsGroupEdit,
        UserListComponent,
        GroupListComponent,
        RxLayout,
        RxFit,
        RxGrid,
        GroupProperties
    },
    data () {
        return {
            propertiesGroups:[],
            selectedKey:[],
            // 表头
            columns: [
                {
                    title: this.$ti18('rxList.action', '操作'),
                    width:200,
                    dataIndex: 'action',
                    scopedSlots: { customRender: 'action' }
                },
                {
                    title: this.i18n('form.groupName','组名'),
                    width:250,
                    dataIndex: 'name',
                    ellipsis: true,
                    scopedSlots: { customRender: 'name' }
                },
                {
                    title:  this.i18n('form.groupKey','组key'),
                    width:100,
                    dataIndex: 'key'
                },


                {
                    title: this.i18n('form.grade','等级'),
                    dataIndex: 'rankLevel',
                    width:100,
                    scopedSlots: { customRender: 'rankLevel' }
                },

            ],
            component:OsGroupEdit,
            comment:this.i18n('form.group','用户组'),
            widthHeight:['800px','500px'],
            tableData:[],

        }
    },

    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "applicationLang", key);
        },
        setParent(record){
            var params={isGrade:false,single:true,dimId:record.dimId,showDimId:false,groupId:record.groupId,isExcludeThis:true};
            if(this.tenantId){
                params.tenantId=this.tenantId;
            }
            Dialog.openGroupDialog(
                {curVm: this,data:params,
                    widthHeight: ['1000px','600px']},function(self,data){
                    if(data && data.groupId){
                        if(data.groupId==record.parentId){
                            self.$message.error(this.i18n('tips.parent','不能选择同一个父级！'));
                            return;
                        }
                        self.changeParent(record.groupId,data.groupId);
                    }
                })
        },
        changeParent(groupId,parentId){
            var self_=this;
            OsGroupApi.changeParent(groupId,parentId).then(result => {
                self_.getDataList();
            })
        },
        rankLevelFilter(rankLevel){
            for(var i=0;i<this.rankData.length;i++){
                if(rankLevel==this.rankData[i].value){
                    return this.rankData[i].title;
                }
            }
            return "";
        },
        delById(ids){
            return OsGroupApi.delOsGroup({ ids: ids.join(',') });
        },
        getDataList(){
            if(!this.queryParam.Q_DIM_ID__S_EQ){
                this.tableData = [];
            }else {
                OsGroupApi.queryGroups(this.queryParam.Q_DIM_ID__S_EQ,"0","no",this.tenantId).then(result => {
                    result.data=this.treeData(result.data);
                    this.tableData = result.data;
                })
            }
            //清除下拉的数据
            this.$refs.table.expandedRowKeys=[];
        },
        addGroup(){
            if(!this.queryParam.Q_DIM_ID__S_EQ){
                this.$message.error(this.i18n('tips.dimension','请选择维度！'));
                return;
            }
            var params={dimId:this.queryParam.Q_DIM_ID__S_EQ};
            if(this.tenantId){
                params.tenantId=this.tenantId;
            }
            var conf={
                component:this.component,
                title:this.$ti18('rxList.newBtn',"添加")  + this.comment,
                widthHeight:this.widthHeight,
                data:params
            };
            this.handleGroupEdit(conf);
        },
        delByGroupIds(ids) {
            if(!ids){
                ids = this.$refs.table.selectedRowKeys;
            }
            let self_ = this;
            this.$confirm({
                title: self_.$ti18('rxMsa.actionTips','操作提示'),
                content: self_.$ti18('rxMsa.delInfo','您确定需要删除选中的记录吗？'),
                okText: self_.$ti18('rxForm.ackBtn','确认'),
                cancelText: self_.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    self_.delById(ids).then(res => {
                        if (res.success && res.code == 200) {
                            self_.getDataList()
                        }
                    })
                },
                onCancel() {
                }
            })
        },
        editGroup(record){
            var conf={
                component:this.component,
                title:this.$ti18('rxList.editBtn','编辑') + this.comment,
                widthHeight:this.widthHeight,
                data:{pkId:record.pkId,dimId:this.queryParam.Q_DIM_ID__S_EQ}
            };
            this.handleGroupEdit(conf);
        },
        editSub(record){
            var params={parentId:record.groupId,dimId:record.dimId};
            if(this.tenantId){
                params.tenantId=this.tenantId;
            }
            var conf={
                component:this.component,
                title:this.i18n('title.addTheSubOf','添加子') + this.comment,
                widthHeight:this.widthHeight,
                data:params
            };
            this.handleGroupEdit(conf);
        },
        handleGroupEdit (conf) {
            var self_ = this;
            var baseConf = {
                "curVm": self_
            };
            let config = Object.assign(baseConf, conf);
            Util.open(config, function (action) {
                if (action == "ok") {
                    self_.getDataList();
                }
            })
        },
        setProprety(record){
            var self=this;
            var config = {
                "curVm": self,
                "data": {"dimId": record.dimId,"groupId":record.groupId},
                component: GroupProperties,
                title: self.i18n('title.management','扩展属性管理'),
                widthHeight:['1024px','600px'],
            };
            Util.open(config, function (action,propertiesGroups) {
                if(action!='ok') return;
                if(propertiesGroups.length>0){
                    var parameter={
                        propertiesGroups:JSON.stringify(propertiesGroups),
                        groupId:record.groupId
                    }
                    osPropertiesGroupApi.saveProperties(parameter).then(res=>{
                    });
                }
            });
        },
        //判断下级是否有子级
        treeData(data){
            for (var i = 0; i <data.length ; i++) {
                if(data[i].childAmount>0){
                    data[i].children=[];
                }
            }
            return data;
        },
        //异步加载组织
        rowExpand(expanded,record){
            var self=this;
            if(expanded&&record.children&&record.children.length==0){
                OsGroupApi.queryGroups(this.queryParam.Q_DIM_ID__S_EQ,record.groupId,"no",this.tenantId).then(result => {
                    result.data=this.treeData(result.data);
                    self.updateData(self.tableData,result.data,record.groupId);
                    this.$refs.table.loadData();
                })
            }
        },
        //更新数据到tableData中
        updateData(tableData,data,groupId){
            for (var i = 0; i <tableData.length ; i++) {
                if(tableData[i].groupId==groupId){
                    tableData[i].children=data;
                    break;
                }else {
                    if(tableData[i].childAmount>0){
                        this.updateData(tableData[i].children,data,groupId);
                    }
                }
            }
        }
    }
}
</script>
<style scoped>
.atbliat{
    height:calc(100% - 80px);
}
.telist{
    height: 20px;
}
.content .table-operator button {
    margin-bottom: 8px;
}
.rx-fit >>>.ant-tabs-bar{
    border-bottom: 0;
}
.ant-row >div{
    padding-right: 0px!important;
}
.rx-table-row-icon{
    overflow: hidden;
    width: auto;
    vertical-align: top;
    line-height: normal;
    margin-top: 1px;
}
.rx-tree-icon{
    display: inline-block;
    float: left;
    font-size: 16px;
    margin-right: 4px;
}
.rx-tree-title{
    white-space: normal;
    overflow: hidden;
}
*>>>.rx-gridBox  .ant-table-row-cell-break-word .ant-table-row-indent,
*>>>.rx-gridBox  .ant-table-row-cell-break-word  .ant-table-row-expand-icon{
    float: left;
    margin-top: 3px;
}
</style>